load("@bazel_skylib//lib:selects.bzl", "selects")
load("@bazel_skylib//rules:common_settings.bzl", "bool_flag")
load("//tools/install:install.bzl", "install", "install_license")
load("//tools/lint:lint.bzl", "add_lint_tests")
load("//tools/skylark:cc.bzl", "cc_library")
load("//tools/skylark:drake_cc.bzl", "cc_nolink_library")

# ---- Logic for choosing which fmt to use. ---

config_setting(
    name = "flag_fmt_repo_pkgconfig",
    flag_values = {
        "//tools/flags:fmt_repo": "pkgconfig",
    },
)

config_setting(
    name = "flag_fmt_repo_default",
    flag_values = {
        "//tools/flags:fmt_repo": "default",
    },
)

config_setting(
    name = "flag_public_repo_default_pkgconfig",
    flag_values = {
        "//tools/flags:public_repo_default": "pkgconfig",
    },
)

selects.config_setting_group(
    name = "flag_fmt_repo_default_pkgconfig",
    match_all = [
        ":flag_fmt_repo_default",
        ":flag_public_repo_default_pkgconfig",
    ],
)

selects.config_setting_group(
    name = "use_pkgconfig",
    match_any = [
        ":flag_fmt_repo_pkgconfig",
        ":flag_fmt_repo_default_pkgconfig",
    ],
)

alias(
    name = "fmt",
    actual = select({
        ":use_pkgconfig": "@pkgconfig_fmt",
        "//conditions:default": "@module_fmt//:fmt",
    }),
    visibility = ["//visibility:public"],
)

# ---- Logic for installing fmt-related files. ---

bool_flag(
    name = "with_user_fmt",
    # This is overridden by our CMakeLists.txt to match the CMake option.
    build_setting_default = False,
)

config_setting(
    name = "is_with_user_true",
    flag_values = {":with_user_fmt": "True"},
)

selects.config_setting_group(
    name = "is_external",
    match_any = [
        ":is_with_user_true",
        ":use_pkgconfig",
    ],
)

cc_nolink_library(
    name = "hdrs",
    visibility = ["//tools/install/libdrake:__pkg__"],
    deps = ["@fmt"],
)

cc_library(
    name = "shared_library_maybe",
    visibility = ["//tools/install/libdrake:__pkg__"],
    deps = select({
        ":is_external": ["@fmt"],
        "//conditions:default": [],
    }),
)

install(
    name = "install_hdrs",
    targets = [":hdrs"],
    hdr_dest = "include",
    hdr_strip_prefix = ["include"],
    guess_hdrs = "ALLOWED_EXTERNALS",
    allowed_externals = ["@module_fmt//:fmt"],
)

install_license(
    name = "install_license",
    doc_dest = "share/doc/fmt",
    licenses = ["@module_fmt//:license"],
)

install(
    name = "install",
    visibility = ["//tools/workspace:__pkg__"],
    deps = select({
        ":is_external": [],
        "//conditions:default": [
            ":install_hdrs",
            ":install_license",
        ],
    }),
)

add_lint_tests()
